<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>文章列表</title>
    <link href="/common/icon2.png" type="image/png" rel="shortcut icon">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/common/list.css">
</head>
<body>
<div class="header">
    <div style="text-align: center;"><img src="/common/icon2.png" alt="" style="height: 50px;"><img
            src="/common/logo.png" alt="BlogFetcher" style="width: 160px;"><b
            style="color: #F44336;">v3.1.1</b></div>
</div>
<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="form-search">
                <form class="layui-form">
                    <div class="layui-form-item">
                        <div class="layui-col-sm1 layui-hide"><label class="layui-form-label ">文章标题：</label></div>
                        <div class="layui-col-sm12">
                            <input class="layui-input layui-input-inline" name="title" autocomplete="off"
                                   placeholder="输入文章的标题"
                                   style="max-width: 290px;width: 100%;display: inline;margin-left: 5px;height: 38px;margin-bottom: 0;">
                            <a class="layui-btn layui-btn-sm layui-bg-black form-btn"  style="height: 38px;line-height: 38px;"
                               lay-submit lay-filter="searchSubmit">搜索
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="layui-row layui-col-space20">
        <div class="layui-col-md12" style="padding-top: 0;">
            <table id="list" class="layui-table" lay-filter="article"></table>
        </div>
    </div>
    <div class="layui-row" style="text-align: center;">
        <fieldset class="layui-elem-field layui-field-title" style="margin-bottom: 0;">
            <legend style="font-size: 14px;color: #333333;margin-left:0;font-weight: 400;">Powered by
                wu-wen-bin／765934806@qq.com
            </legend>
            <p style="margin-top: 10px;"><a href="https://gitee.com/miyakowork/blog-fetcher" target="_blank"
                                            style="font-size: 14px;color: #878787;">获取源码</a></p>
        </fieldset>
    </div>
</div>

<script type="text/html" id="toolbarBtn">
    <div class="layui-btn-container layui-hide">
        <a class="layui-btn layui-btn-sm layui-bg-cyan" href="/login"
           th:if="${#session==null || #session.getAttribute('user') == null}">登录系统</a>
        <a class="layui-btn layui-btn-sm layui-bg-blue" href="/parse">抓取文章内容</a>
        <a class="layui-btn layui-btn-sm layui-bg-blue" href="/system">系统管理</a>
        <a class="layui-btn layui-btn-sm layui-bg-blue" id="showLogs">更新日志</a>
    </div>
</script>
<script src="/layui/layui.js"></script>
<script src="/xmSelect/xmSelect.js"></script>
<script th:inline="javascript">
    var $ = layui.$;

    function containerHeight() {
        var formHeight = $(".layui-form").height();
        var containerHeight = $(window).height() - (180 + formHeight);
        $(".card-container").css("height", containerHeight + "px");
    }

    window.onload = function () {
        containerHeight();
    };
    $(window).resize(function () {
        containerHeight();
    })
    var isLogin = [[${#session!=null && #session.getAttribute('user') != null}]];

    $("#addNewTag").click(function () {
        layer.prompt({
            title: "输入标签名称"
        }, function (value, index, elem) {
            $.post("/system/cateAdd", {name: value}, function (resp) {
                if (resp.code === 0) {
                    layer.close(index);
                }
                layer.msg(resp.msg);
                setTimeout(function () {
                    location.reload();
                }, 500);
            });
        });
    });
    layui.use(['form', 'element', 'table', 'util', 'laydate', 'jquery'], function () {
        var form = layui.form;
        var element = layui.element;
        var table = layui.table;
        var util = layui.util;
        var laydate = layui.laydate;
        var $ = layui.jquery;

        //初始化表格
        var tableIns = table.render({
                elem: '#list'
                , url: '/list'
                , method: 'post'
                , contentType: "application/json"
                , page: {
                    layout: ['prev', 'page', 'next', 'count', 'limit']
                }
                , skin: 'line'
                , autoSort: false
                , limit: 10
                , height: 'full-' + (160 + $(".layui-form").height())
                , limits: [10, 15, 25, 30, 50]
                , toolbar: false //开启头部工具栏，并为其绑定左侧模板
                , defaultToolbar: false
                , parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.data.total,
                        "data": res.data.records
                    };
                }
                , request: {
                    pageName: 'pageNo'
                    , limitName: 'pageSize'
                }
                , where: {
                    sIds: getSeriesIdArr().join(",")
                }
                , cols: [
                    [
                        {field: 'id', title: '序号', sort: true, width: 65, type: 'numbers', hide: true}
                        , {field: 'author', title: '作者', sort: true, width: 120, hide: true}
                        , {
                        field: 'type', title: '来源', width: 80, sort: true, hide: true, templet: function (d) {
                            return '<img src="/logo/' + d.type + '.ico" alt="' + d.typeCnName + '" style="width: 25px;height: 25px;"/>'
                        }
                    }
                        , {
                        field: 'title_modified',
                        title: '标题（编辑后）',
                        sort: true,
                        edit: (isLogin ? 'text' : false),
                        hide: true,
                        templet: function (d) {
                            return '<a href="/article?id=' + d.id + '" target="_blank" class="layui-table-link">' + ((d.title_modified === undefined || d.title_modified === null) ? d.title : d.title_modified) + '</a>';
                        }
                    }, {
                        field: 'title', title: '标题（原标题）', sort: true, templet: function (d) {
                            return '<a href="/article?id=' + d.id + '" target="_blank" class="layui-table-link">' + d.title + '</a>';
                        }
                    }
                        , {
                        field: 'link', title: '原文', width: 60, hide: true, templet: function (d) {
                            return '<a href="' + d.link + '" target="_blank" class="layui-table-link">查看</a>';
                        }
                    }, {
                        field: '', title: '操作', width: 100, hide: true, templet: function (d) {
                            if (isLogin) {
                                return '<a href="javascript:delArticle(' + d.id + ',\'' + d.title + '\');" class="layui-btn layui-bg-black layui-btn-xs"><i class="layui-icon layui-icon-close"></i>删除</a>';
                            } else {
                                return '-';
                            }
                        }
                    }, {
                        title: '分类标签', hide: true, width: (isLogin ? 320 : 200), templet: function (d) {
                            if (isLogin) {
                                return '<div id="XM-cates' + d.id + '" ></div>'
                            } else {
                                if (d.cates === null || d.cates.length === 0) {
                                    return '-';
                                } else {
                                    var ccc = d.cates.filter(function (c) {
                                        return c.selected !== undefined && c.selected;
                                    }).map(function (c) {
                                        return '<span class="layui-badge layui-bg-blue">' + c.name + '</span>';
                                    });
                                    return ccc.length > 0 ? ccc.join("&nbsp;") : "-";
                                }
                            }
                        }
                    }, {
                        title: '系列', hide: true, width: (isLogin ? 250 : 150), templet: function (d) {
                            if (isLogin) {
                                return '<div id="XM-series' + d.id + '" ></div>'
                            } else {
                                if (d.series === null || d.series.length === 0) {
                                    return '-';
                                } else {
                                    var sss = d.series.filter(function (c) {
                                        return c.selected !== undefined && c.selected;
                                    }).map(function (c) {
                                        return '<span class="layui-badge layui-bg-cyan">' + c.name + '</span>';
                                    });
                                    return sss.length > 0 ? sss.join("&nbsp;") : "-";
                                }
                            }
                        }
                    }, {
                        field: 'publishTime', title: '发布时间', width: 130, hide: true, sort: true, templet: function (d) {
                            return util.toDateString(d.publish_time, 'yyyy-MM-dd');
                        }
                    }
                        , {
                        field: 'fetchTime', title: '爬取时间', width: 130, hide: true, sort: true, templet: function (d) {
                            return util.toDateString(d.fetch_time, 'yyyy-MM-dd');
                        }
                    }
                    ]
                ],
                done: function (res) {
                    if (isLogin) {
                        //修改一些css样式, 这里虽然能够使用, 但是还是不太友好, 努力中...
                        var cells = document.querySelectorAll('div[lay-id="list"] .layui-table-cell');
                        for (var i = 0; i < cells.length; i++) {
                            //cells[i].style.overflow = 'unset';
                            cells[i].style.height = 'auto';
                        }
                        //渲染多选
                        var xmC, xmS;
                        res.data.forEach(function (item) {
                                xmC = xmSelect.render({
                                        el: '#XM-cates' + item.id,
                                        size: 'small',
                                        model: {
                                            type: 'fixed',
                                            label: {
                                                type: 'block',//使用方块显示
                                                block: {
                                                    //最大显示数量, 0:不限制
                                                    showCount: 3,
                                                    //是否显示删除图标
                                                    showIcon: true
                                                }
                                            }
                                        },
                                        prop: {value: 'id'},
                                        filterable: true,
                                        paging: true,
                                        pageSize: 10,
                                        height: '360px',
                                        data: item.cates,
                                        on: function (data) {
                                            var arr = data.arr;
                                            var ids = arr.map(function (item) {
                                                return item.id;
                                            });
                                            $.post("/system/cateEdit", {
                                                articleId: item.id,
                                                cateIds: ids.join(",")
                                            }, function (resp) {
                                                layer.msg(resp.msg);
                                            });
                                        },
                                        show: function () {
                                            window.__xmSelectTop = null;
                                            var sel = this.el;
                                            //下拉框内容 body 的高度
                                            var height = $(sel).find(".xm-body").outerHeight(true);
                                            //坐标
                                            var y = $(sel).offset().top;
                                            //浏览器可视范围高度
                                            var windowHeight = $(window).height();
                                            if (y + height + 50 > windowHeight) {
                                                //5 表示 padding-top
                                                window.__xmSelectTop = y - 5 - height;
                                            }
                                        },
                                        hide: function () {
                                            window.__xmSelectTop = null;
                                        }
                                    }
                                );
                                xmS = xmSelect.render({
                                    el: '#XM-series' + item.id,
                                    size: 'small',
                                    model: {
                                        type: 'fixed',
                                        label: {
                                            type: 'block',//使用方块显示
                                            block: {
                                                //最大显示数量, 0:不限制
                                                showCount: 3,
                                                //是否显示删除图标
                                                showIcon: true
                                            }
                                        }
                                    },
                                    prop: {value: 'id'},
                                    filterable: true,
                                    paging: true,
                                    pageSize: 10,
                                    height: '360px',
                                    data: item.series,
                                    on: function (data) {
                                        var arr = data.arr;
                                        var ids = arr.map(function (item) {
                                            return item.id;
                                        });
                                        $.post("/system/seriesEdit", {
                                            articleId: item.id,
                                            seriesIds: ids.join(",")
                                        }, function (resp) {
                                            layer.msg(resp.msg);
                                        });
                                    },
                                    show: function () {
                                        window.__xmSelectTop = null;
                                        var sel = this.el;
                                        //下拉框内容 body 的高度
                                        var height = $(sel).find(".xm-body").outerHeight(true);
                                        //坐标
                                        var y = $(sel).offset().top;
                                        //浏览器可视范围高度
                                        var windowHeight = $(window).height();
                                        if (y + height + 50 > windowHeight) {
                                            //5 表示 padding-top
                                            window.__xmSelectTop = y - 5 - height;
                                        }
                                    },
                                    hide: function () {
                                        window.__xmSelectTop = null;
                                    }
                                });
                            }
                        );
                    }
                }
            })
        ;

        //搜索
        var cates = [], types = [];
        var title = "";
        var dateStart = "", dateEnd = "";
        var fetchStart = "", fetchEnd = "";
        laydate.render({
            elem: '#publishTime'
            , range: true
            , done: function (value, date, endDate) {
                if (date.year && endDate.year) {
                    dateStart = date.year + "-" + (date.month < 10 ? '0' + date.month : date.month) + "-" + (date.date < 10 ? '0' + date.date : date.date);
                    dateEnd = endDate.year + "-" + (endDate.month < 10 ? '0' + endDate.month : endDate.month) + "-" + (endDate.date < 10 ? '0' + endDate.date : endDate.date);
                } else {
                    dateStart = "";
                    dateEnd = "";
                }
            }
        });

        laydate.render({
            elem: '#fetchTime'
            , range: true
            , done: function (value, date, endDate) {
                if (date.year && endDate.year) {
                    fetchStart = date.year + "-" + (date.month < 10 ? '0' + date.month : date.month) + "-" + (date.date < 10 ? '0' + date.date : date.date);
                    fetchEnd = endDate.year + "-" + (endDate.month < 10 ? '0' + endDate.month : endDate.month) + "-" + (endDate.date < 10 ? '0' + endDate.date : endDate.date);
                } else {
                    fetchStart = "";
                    fetchEnd = "";
                }
            }
        });

        form.on('checkbox(cates)', function (data) {
            var checked = data.elem.checked;
            if (checked) cates.push(data.value);
            else cates.remove(data.value)
            title = $("input[name=title]").val();
            search(types, cates, title, dateStart, dateEnd, fetchStart, fetchEnd);
        });
        form.on('checkbox(types)', function (data) {
            var checked = data.elem.checked;
            if (checked) types.push(data.value);
            else types.remove(data.value)
            title = $("input[name=title]").val();
            search(types, cates, title, dateStart, dateEnd);
        });
        form.on('submit(searchSubmit)', function (data) {
            title = $("input[name=title]").val();
            search(types, cates, title, dateStart, dateEnd, fetchStart, fetchEnd)
            return false;
        });
        $("a#clearTitle").click(function () {
            $("input[name=title]").val("");
        });
        $(".layui-card").click(function () {
            var $this = $(this);
            $this.toggleClass("active");
            $this.find(".layui-card-header>i").toggleClass("layui-hide");
            var sIds = getSeriesIdArr().join(",");
            location.href = "/list?sId=" + sIds;
        });

        /**
         * 获取左侧 card 的勾选的 id
         * @returns {*[]}
         */
        function getSeriesIdArr() {
            var $seriesCards = $(".series-card");
            var sids = [];
            for (var i = 0; i < $seriesCards.length; i++) {
                var $curCard = $($seriesCards).eq(i);
                if ($curCard.hasClass("active")) {
                    sids.push($curCard.data("id"));
                }
            }
            return sids;
        }

        function search(types, cateIds, title, dateStart, dateEnd, fetchStart, fetchEnd) {
            tableIns.reload({
                where: {
                    'title': title,
                    'types': types,
                    "cateIds": cateIds,
                    "dateStart": dateStart,
                    "dateEnd": dateEnd,
                    "fetchStart": fetchStart,
                    "fetchEnd": fetchEnd,
                    "sIds": getSeriesIdArr().join(",")
                },
                page: {
                    curr: 1
                }
            });
            return false;
        }

        //排序
        table.on('sort(article)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            tableIns.reload({
                initSort: obj
                , where: {
                    orderField: obj.field
                    , orderDirection: obj.type
                }
            });
        });

        //监听单元格编辑
        table.on('edit(article)', function (obj) {
            var data = obj.data;
            var confirmMsg = '确定修改标题为：' + util.escape(obj.value) + '吗？';
            layer.confirm(confirmMsg, function () {
                $.post("/system/titleEdit", {
                    articleId: data.id,
                    title: obj.value
                }, function (resp) {
                    if (resp.code === 0) {
                        layer.msg("修改成功");
                        tableIns.reload({page: {curr: 1}});
                    } else {
                        layer.msg("修改失败，" + resp.msg);
                    }
                });
            })
        });

        //更新日志
        $("#showLogs").click(function () {
            layer.open({
                type: 2,
                content: "/logs",
                title: "更新日志（<b style='color: #F44336;'>项目介绍往下拉，在底部</b>）",
                area: ['700px', '600px'],
                shadeClose: true,
                shade: [0.3, '#cccccc'],
                offset: '150px'
            })
        });

        var down = true;
        var curHeight = $("#tagDiv").height();
        $("#tagBtn").click(function () {
            var h = down ? 200 : curHeight;
            $("#tagDiv").animate({
                height: h + "px"
            }, function () {
                $(window).trigger("resize");
            });

            down = !down;
        });
    })
    ;
</script>
<script>
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };

    function delArticle(aId, title) {
        layer.confirm("确认删除以下文章吗？<br/><b>" + title + "</b>", function (index) {
            layui.$.post("/system/delete", {articleId: aId}, function (resp) {
                if (resp.code === 0) {
                    layui.layer.msg("删除成功！");
                    setTimeout(function () {
                        location.reload();
                    }, 567);
                } else {
                    layui.layer.msg(resp.msg);

                }
            });
            layer.close(index);
        });

    }
</script>
</body>
</html>